<?php
/**
 * @fileName:Response.php
 * @project: miaosang
 * @nameSpace:miaosang\yii2\response
 * @Class Response
 * @author : 吐火青蛙
 * @user : 吐火青蛙
 * @date : 2021-08-17 12:48
 * @desc : Response
 * @Copyright (c)  2021,All Rights Reserved.
 */
namespace miaosang\yii2\response;
use yii\helpers\Json;
trait Response
{

	/**
	 * @desc 成功返回
	 * @param $msg
	 * @param $data
	 * @param  int  $code
	 */

	public function Success( $data, $msg = '数据处理成功',$code = 200){
		$jsonData = [
			'status' => '200',
			'msg' =>(string) $msg,
			'data' => $data,
			'code' => (string)$code,
		];
		$jsonStr = Json::encode($jsonData, JSON_UNESCAPED_UNICODE);
		if (!$jsonStr) {
			self::Error('数据JSONENCODE异常，数据包含特殊字符或者不符合格式',500);
		}
		//判断是否有callback函数
		\yii::$app->response->statusCode = 200;
		\yii::$app->response->headers->add("Content-type","application/json;charset=utf-8");
		\yii::$app->response->format= 'json';
		\yii::$app->response->content= $jsonStr;
		\yii::$app->response->send();
		\yii::$app->end();
	}

	/**
	 * @name Error
	 * @desc 返回错误的代码信息
	 * @param $msg
	 * @param int $error
	 * @throws \yii\base\ExitException
	 */
	public function Error($msg,$error = 400){
		\yii::$app->response->headers->add("Content-type","application/json;charset=utf-8");
		$data = [
			'status' => '200',
			'msg' => $msg,
			'data' => [],
			'error' => (string)$error,
		];
		$jsonStr = Json::encode($data, JSON_UNESCAPED_UNICODE);
		\yii::$app->response->statusCode = '200';
		\yii::$app->response->format= 'json';
		\yii::$app->response->content= $jsonStr;
		\yii::$app->response->send();
		\yii::$app->end();
	}

	/**
	 * @name BadRequest
	 * @desc 无效的请求数据
	 */

	public function BadRequest(){
		\yii::$app->response->statusCode = '400';
		\yii::$app->response->data="无效的请求数据";
		\yii::$app->response->send();
		\yii::$app->end();
	}

	/**
	 * @name NoAuth
	 * @desc 未授权的访问
	 */
	public function NoAuth(){
		\yii::$app->response->statusCode = '401';
		\yii::$app->response->data="未授权的访问";
		\yii::$app->response->send();
		\yii::$app->end();
	}

	/**
	 * @name Forbidden
	 * @desc 禁止跨权访问
	 */
	public  function Forbidden(){
		\yii::$app->response->statusCode = '403';
		\yii::$app->response->data="没有权限禁止访问";
		\yii::$app->response->send();
		\yii::$app->end();
	}

	/**
	 * @name NotFound
	 * @desc 资源不存在返回异常
	 */
	public function NotFound(){
		\yii::$app->response->statusCode = '404';
		\yii::$app->response->data="资源不存在";
		\yii::$app->response->send();
		\yii::$app->end();
	}


}